<template>
  <div class="home-container">
    <div class="banner">
      <div class="banner-content">
        <h1>美味送到家</h1>
        <p>品质保障，专业配送</p>
        <div class="banner-search">
          <el-input 
            placeholder="搜索附近美食..." 
            prefix-icon="el-icon-search"
            v-model="searchText"
            @keyup.enter.native="onSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="onSearch">搜索</el-button>
          </el-input>
        </div>
      </div>
    </div>
    
    <div class="content-wrap">
      <!-- 分类导航 -->
      <div class="category-container">
        <div class="category-title">美食分类</div>
        <div class="category-list">
          <div 
            v-for="category in categories" 
            :key="category.id" 
            class="category-item"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            <div class="category-icon-wrap">
              <i :class="['category-icon', 'el-icon-' + getIconByCategory(category.name)]"></i>
            </div>
            <span>{{ category.name }}</span>
          </div>
        </div>
      </div>
      
      <!-- 推荐轮播 -->
      <div class="recommend-container">
        <div class="section-title">
          <span class="title-text">美食推荐</span>
          <span class="title-more" @click="showMoreProducts">更多推荐 <i class="el-icon-arrow-right"></i></span>
        </div>
        
        <div class="recommended-products" v-loading="recommendLoading">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="product in recommendedProducts" :key="product.id">
              <div class="product-card" @click="goToProductDetail(product.id)">
                <div class="product-image">
                  <el-image 
                    :src="product.image || `https://picsum.photos/300/200?random=${product.id}`" 
                    fit="cover">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                  <div class="product-tags" v-if="product.tags && product.tags.length > 0">
                    <el-tag v-for="(tag, i) in product.tags" :key="i" size="mini" :type="getTagType(tag)">
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
                <div class="product-info">
                  <h3 class="product-name">{{ product.name }}</h3>
                  <div class="product-meta">
                    <span class="product-price">¥{{ product.price }}</span>
                    <span class="product-sales">销量 {{ product.sales }}</span>
                  </div>
                  <div class="product-shop">{{ product.merchantName || '未知商家' }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
          
          <div class="empty-data" v-if="recommendedProducts.length === 0 && !recommendLoading">
            <i class="el-icon-food"></i>
            <p>暂无推荐美食</p>
          </div>
        </div>
      </div>
      
      <!-- 商家列表 -->
      <div class="merchant-container">
        <div class="section-title">
          <span class="title-text">附近商家</span>
        </div>
        <div class="merchant-filter">
          <el-radio-group v-model="sortType" size="small">
            <el-radio-button label="default">综合排序</el-radio-button>
            <el-radio-button label="rating">评分最高</el-radio-button>
            <el-radio-button label="distance">距离最近</el-radio-button>
          </el-radio-group>
        </div>
        
        <div class="merchant-list" v-loading="loading">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" v-for="merchant in filteredMerchants" :key="merchant.id">
              <div class="merchant-card" @click="goToShop(merchant.id)">
                <div class="merchant-card-header">
                  <div class="merchant-logo">
                    <img :src="merchant.shopLogo || 'https://picsum.photos/200/200?random=' + merchant.id" alt="商家logo">
                  </div>
                  <div class="merchant-status">
                    <el-tag size="mini" type="success" v-if="merchant.status === 1">营业中</el-tag>
                    <el-tag size="mini" type="info" v-else>休息中</el-tag>
                  </div>
                </div>
                <div class="merchant-card-body">
                  <div class="merchant-name">{{ merchant.shopName }}</div>
                  <div class="merchant-rating">
                    <el-rate :value="merchant.rating" disabled text-color="#ff9900" score-template="{value}"></el-rate>
                    <span class="rating-value">{{ merchant.rating }}</span>
                    <span class="monthly-sales">月售 {{ merchant.monthlySales || 0 }}+</span>
                  </div>
                  <div class="merchant-price">
                    <span>起送 ¥{{ merchant.minPrice || 0 }}</span>
                    <span class="delivery-fee">配送费 ¥{{ merchant.deliveryFee || 5 }}</span>
                  </div>
                  <div class="merchant-delivery">
                    <i class="el-icon-time"></i>
                    <span class="delivery-time">{{ merchant.deliveryTime || '30-45' }} 分钟</span>
                    <span class="delivery-distance"><i class="el-icon-location"></i> 1.5km</span>
                  </div>
                  <div class="merchant-tags">
                    <el-tag size="mini" v-for="(tag, index) in merchant.tags || []" :key="index">{{ tag }}</el-tag>
                  </div>
                  <div class="merchant-promotion" v-if="merchant.promotion">
                    <div class="promotion-badge">优惠</div>
                    <div class="promotion-text">{{ merchant.promotion }}</div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
          
          <div class="empty-data" v-if="filteredMerchants.length === 0 && !loading">
            <i class="el-icon-shopping-bag-1"></i>
            <p>暂无商家数据</p>
            <el-button type="primary" @click="fetchData">刷新试试</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getNearbyShops } from '@/api/user';

export default {
  name: 'UserHome',
  data() {
    return {
      loading: false,
      recommendLoading: false,
      recommendedProducts: [],
      categories: [],
      merchants: [],
      selectedCategory: null,
      sortType: 'default',
      searchText: '',
      // 临时数据，实际应从API获取
      tempCategories: [
        { id: 1, name: '快餐' },
        { id: 2, name: '正餐' },
        { id: 3, name: '小吃' },
        { id: 4, name: '饮品' },
        { id: 5, name: '水果' }
      ],
      tempMerchants: [
        {
          id: 1,
          shopName: '冰淇淋专卖',
          shopLogo: '',
          rating: 4.8,
          monthlySales: 1500,
          minPrice: 15,
          deliveryFee: 4,
          deliveryTime: '20-30',
          categoryId: 4,
          status: 1,
          tags: ['甜品', '冰淇淋'],
          promotion: '满30减10'
        },
        {
          id: 2,
          shopName: '示例餐厅',
          shopLogo: '',
          rating: 4.7,
          monthlySales: 1200,
          minPrice: 20,
          deliveryFee: 5,
          deliveryTime: '30-45',
          categoryId: 1,
          status: 1,
          tags: ['特色套餐', '新店'],
          promotion: '首单减5元'
        },
        {
          id: 3,
          shopName: '健康餐厅',
          shopLogo: '',
          rating: 4.5,
          monthlySales: 900,
          minPrice: 25,
          deliveryFee: 6,
          deliveryTime: '40-50',
          categoryId: 2,
          status: 0,
          tags: ['营养套餐', '健康食品'],
          promotion: '满30减8'
        },
        {
          id: 4,
          shopName: '绿色沙拉',
          shopLogo: '',
          rating: 4.6,
          monthlySales: 800,
          minPrice: 22,
          deliveryFee: 5,
          deliveryTime: '30-40',
          categoryId: 2,
          status: 1,
          tags: ['沙拉', '轻食'],
          promotion: '下单立减3元'
        },
        {
          id: 5,
          shopName: '奶茶工坊',
          shopLogo: '',
          rating: 4.9,
          monthlySales: 2000,
          minPrice: 18,
          deliveryFee: 4,
          deliveryTime: '25-35',
          categoryId: 4,
          status: 1,
          tags: ['奶茶', '甜品'],
          promotion: '第二杯半价'
        },
        {
          id: 6,
          shopName: '水果天地',
          shopLogo: '',
          rating: 4.7,
          monthlySales: 1100,
          minPrice: 30,
          deliveryFee: 6,
          deliveryTime: '30-45',
          categoryId: 5,
          status: 1,
          tags: ['新鲜水果', '切盘'],
          promotion: '满50减15'
        }
      ]
    }
  },
  computed: {
    filteredMerchants() {
      let result = this.merchants
      
      // 根据分类筛选
      if (this.selectedCategory) {
        result = result.filter(item => item.categoryId === this.selectedCategory)
      }
      
      // 根据关键词筛选
      if (this.searchText) {
        const keyword = this.searchText.toLowerCase()
        result = result.filter(item => 
          item.shopName.toLowerCase().includes(keyword) || 
          (item.tags && item.tags.some(tag => tag.toLowerCase().includes(keyword)))
        )
      }
      
      // 根据排序类型排序
      if (this.sortType === 'rating') {
        result = result.sort((a, b) => b.rating - a.rating)
      } else if (this.sortType === 'distance') {
        // 这里应该根据距离排序，暂时随机排序
        result = result.sort(() => Math.random() - 0.5)
      }
      
      return result
    }
  },
  created() {
    this.fetchData()
    this.fetchRecommendedProducts()
  },
  methods: {
    fetchData() {
      this.loading = true;
      
      // 获取分类数据（暂时使用临时数据）
      this.categories = this.tempCategories;
      
      // 获取附近商家
      const params = {
        latitude: 30.5928, // 模拟的位置
        longitude: 114.3055,
        keyword: this.searchText || undefined,
        categoryId: this.selectedCategory || undefined,
        page: 1,
        size: 10
      };
      
      getNearbyShops(params)
        .then(res => {
          if (res.code === 200) {
            this.merchants = res.data.list || [];
          } else {
            this.$message.error(res.message || '获取商家数据失败');
            // 如果接口调用失败，加载临时数据
            this.merchants = this.tempMerchants || [];
          }
        })
        .catch(err => {
          console.error('获取商家列表失败', err);
          this.$message.error('获取商家列表失败');
          // 接口异常时加载临时数据
          this.merchants = this.tempMerchants || [];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    fetchRecommendedProducts() {
      this.recommendLoading = true;
      
      this.$http.get('/api/user/shop/recommended-products')
        .then(res => {
          const { data } = res;
          if (data.code === 200) {
            this.recommendedProducts = data.data || [];
            
            // 获取每个商品的商家名称
            this.recommendedProducts.forEach(product => {
              this.fetchMerchantName(product);
            });
          } else {
            this.$message.error(data.message || '获取推荐商品失败');
          }
        })
        .catch(err => {
          console.error('获取推荐商品失败', err);
        })
        .finally(() => {
          this.recommendLoading = false;
        });
    },
    
    fetchMerchantName(product) {
      if (!product.merchantId) return;
      
      this.$http.get(`/api/user/shop/${product.merchantId}`)
        .then(res => {
          const { data } = res;
          if (data.code === 200 && data.data) {
            this.$set(product, 'merchantName', data.data.shopName || '未知商家');
          }
        })
        .catch(err => {
          console.error('获取商家信息失败', err);
        });
    },
    
    selectCategory(categoryId) {
      if (this.selectedCategory === categoryId) {
        this.selectedCategory = null
      } else {
        this.selectedCategory = categoryId
      }
    },
    onSearch() {
      if (this.searchText) {
        console.log('Searching for:', this.searchText); // Debug log
        this.$router.push({
          path: '/search-results',
          query: { q: this.searchText }
        })
      }
    },
    goToShop(id) {
      this.$router.push(`/shop/${id}`)
    },
    getIconByCategory(name) {
      const iconMap = {
        '快餐': 'burger',
        '正餐': 'dish',
        '小吃': 'ice-cream',
        '饮品': 'coffee',
        '水果': 'cherry'
      }
      return iconMap[name] || 'food'
    },
    showMoreProducts() {
      // 暂时简单实现，跳转到首页全部商品部分
      this.$nextTick(() => {
        document.querySelector('.merchant-container').scrollIntoView({ behavior: 'smooth' });
      });
    },
    goToProductDetail(id) {
      this.$router.push(`/product/${id}`);
    },
    getTagType(tag) {
      if (tag.includes('折扣')) {
        return 'danger';
      } else if (tag === '热销') {
        return 'warning';
      } else if (tag === '新品') {
        return 'success';
      }
      return '';
    }
  }
}
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}
.banner {
  height: 280px;
  background: linear-gradient(135deg, #ff6000, #ff9000);
  background-image: url('https://picsum.photos/1920/600?blur=2');
  background-size: cover;
  background-position: center;
  background-blend-mode: overlay;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  text-align: center;
  position: relative;
}
.banner::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
}
.banner-content {
  position: relative;
  z-index: 1;
  width: 90%;
  max-width: 600px;
}
.banner-content h1 {
  font-size: 42px;
  margin-bottom: 15px;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);
  animation: fadeInDown 1s;
}
.banner-content p {
  font-size: 20px;
  margin-bottom: 25px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
  animation: fadeInUp 1s;
}
.banner-search {
  animation: fadeIn 1.5s;
}
.content-wrap {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  margin-top: -50px;
  position: relative;
  z-index: 2;
}
.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.title-text {
  font-size: 20px;
  font-weight: bold;
  position: relative;
  padding-left: 12px;
  color: #333;
}
.title-text::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background-color: #ff6000;
  border-radius: 2px;
}
.title-more {
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}
.title-more:hover {
  color: #ff6000;
}
.category-container {
  background-color: white;
  border-radius: 8px;
  padding: 25px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transform: translateY(0);
  transition: transform 0.3s;
}
.category-container:hover {
  transform: translateY(-5px);
}
.category-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  position: relative;
  padding-left: 12px;
}
.category-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background-color: #ff6000;
  border-radius: 2px;
}
.category-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 18%;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}
.category-item:hover .category-icon-wrap {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(255, 96, 0, 0.15);
}
.category-icon-wrap {
  width: 65px;
  height: 65px;
  background-color: #fff7f2;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  transition: all 0.3s;
  border: 2px solid transparent;
}
.category-item.active .category-icon-wrap {
  background-color: #fff0e6;
  border-color: #ff6000;
  box-shadow: 0 10px 20px rgba(255, 96, 0, 0.15);
}
.category-item:hover {
  color: #ff6000;
}
.category-item.active {
  color: #ff6000;
}
.category-icon {
  font-size: 30px;
  color: #ff6000;
}
.recommend-container {
  margin-bottom: 30px;
  background-color: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
.recommended-products {
  margin-top: 20px;
}
.recommended-products .product-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid #f0f0f0;
  cursor: pointer;
}
.recommended-products .product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  border-color: #ffe0cc;
}
.recommended-products .product-image {
  height: 160px;
  position: relative;
}
.recommended-products .product-image .el-image {
  width: 100%;
  height: 100%;
}
.recommended-products .product-tags {
  position: absolute;
  top: 10px;
  left: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
.recommended-products .product-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.recommended-products .product-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.recommended-products .product-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}
.recommended-products .product-price {
  color: #ff6000;
  font-weight: bold;
}
.recommended-products .product-sales {
  font-size: 12px;
  color: #999;
}
.recommended-products .product-shop {
  font-size: 12px;
  color: #666;
}
.merchant-container {
  background-color: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
.merchant-filter {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}
.merchant-list {
  min-height: 300px;
}
.merchant-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid #f0f0f0;
}
.merchant-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  border-color: #ffe0cc;
}
.merchant-card-header {
  position: relative;
}
.merchant-logo {
  width: 100%;
  height: 150px;
  overflow: hidden;
}
.merchant-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}
.merchant-card:hover .merchant-logo img {
  transform: scale(1.05);
}
.merchant-status {
  position: absolute;
  top: 10px;
  right: 10px;
}
.merchant-card-body {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}
.merchant-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.merchant-rating {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.rating-value {
  margin-left: 5px;
  color: #ff9900;
  font-weight: bold;
}
.monthly-sales {
  margin-left: 15px;
  color: #999;
}
.merchant-price, .merchant-delivery {
  margin-bottom: 10px;
  color: #666;
  font-size: 13px;
}
.delivery-fee {
  margin-left: 15px;
}
.delivery-time, .delivery-distance {
  color: #666;
  margin-right: 10px;
}
.merchant-tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
.merchant-promotion {
  display: flex;
  align-items: center;
  margin-top: auto;
  background-color: #fff9f5;
  padding: 8px;
  border-radius: 4px;
  font-size: 13px;
}
.promotion-badge {
  background-color: #ff6000;
  color: white;
  padding: 2px 6px;
  border-radius: 2px;
  margin-right: 8px;
  font-size: 12px;
}
.promotion-text {
  color: #ff6000;
}
.empty-data {
  padding: 60px 0;
  text-align: center;
  color: #999;
}
.empty-data i {
  font-size: 50px;
  margin-bottom: 15px;
  color: #ddd;
}
.empty-data p {
  margin-bottom: 20px;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
@keyframes fadeInDown {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeInUp {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .category-item {
    width: 30%;
  }
  .banner {
    height: 220px;
  }
  .banner-content h1 {
    font-size: 32px;
  }
  .banner-content p {
    font-size: 16px;
  }
  .content-wrap {
    margin-top: -30px;
  }
}
@media (max-width: 576px) {
  .category-item {
    width: 45%;
  }
}
</style> 